package com.snow.service.attach.impl;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.snow.constant.ErrorConstant;
import com.snow.dao.AttachDao;
import com.snow.exception.SiteException;
import com.snow.pojo.dto.AttachDto;
import com.snow.pojo.model.AttachDomain;
import com.snow.service.attach.AttachService;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.stereotype.Service;

import java.util.List;

/**
 * @Description:
 * @author: snow
 * @Date: 2020-02-01
 **/
@Service
public class AttachServiceImpl implements AttachService {
    @Autowired
    private AttachDao attachDao;
    private static Logger logger = LoggerFactory.getLogger(AttachServiceImpl.class);

    @Override
    @CacheEvict(value="attachCache",allEntries = true,beforeInvocation = true)
    public void addAttach(AttachDomain attachDomain) {
        if(attachDomain == null || StringUtils.isBlank(attachDomain.getFkey())){
            throw SiteException.withErrorCode(ErrorConstant.Commons.PARAM_IS_EMPTY);
        }
        attachDao.addAttach(attachDomain);
    }

    @Override
    @CacheEvict(value = "attachCache",allEntries = true,beforeInvocation = true)
    public void batchAddAttach(List<AttachDomain> list) {
        if(list == null || list.size() <=0){
            throw SiteException.withErrorCode(ErrorConstant.Att.ADD_NEW_ATT_FAIL);
        }
        attachDao.batchAttach(list);
    }

    @Override
    @CacheEvict(value="attachCache",allEntries = true,beforeInvocation = true)
    public void deleteAttach(Integer id) {
        if(id == null){
            throw SiteException.withErrorCode(ErrorConstant.Commons.PARAM_IS_EMPTY);
        }
        attachDao.deleteAttachById(id);
    }

    @Override
    @CacheEvict(value="attachCache",allEntries = true,beforeInvocation = true)
    public void updateAttach(AttachDomain attachDomain) {
        if(attachDomain == null){
            throw SiteException.withErrorCode(ErrorConstant.Commons.PARAM_IS_EMPTY);
        }
        attachDao.updateAttach(attachDomain);
    }

    @Override
    @Cacheable(value="attachCache",key="'attachById_' + #p0")
    public AttachDto getAttachById(Integer id) {
       if(id != null){
           AttachDto attach = attachDao.getAttachById(id);
           return attach;
       }
        return null;
    }

    @Override
    @Cacheable(value="attachCache",key="'attaches_' + #p0")
    public PageInfo<AttachDto> getAttaches(Integer pageNum, Integer limit) {
        PageHelper.startPage(pageNum,limit);
        List<AttachDto> attaches = attachDao.getAttaches();
        PageInfo<AttachDto> pageInfo = new PageInfo<>(attaches);

        return pageInfo;
    }
}
